{
  buildPgrxExtension,
  cargo-pgrx_0_16_1,
  postgresql,
  fetchFromGitHub,
  lib,
  postgresqlTestExtension,
}:

buildPgrxExtension (finalAttrs: {
  pname = "pgvectorscale";
  version = "0.9.0";

  src = fetchFromGitHub {
    owner = "timescale";
    repo = "pgvectorscale";
    tag = finalAttrs.version;
    hash = "sha256-whGTJI73wifYkleC+aAbDV4nhwls3uFs1xKcB0zLDRo=";
  };

  doCheck = false;

  cargoHash = "sha256-uaRKUtsUdZPcrQLAixCiEphXQqdsRhi8nSfh9b3w0ao=";
  cargoPatches = [
    ./add-Cargo.lock.patch
  ];

  cargoPgrxFlags = [
    "-p"
    "vectorscale"
  ];

  inherit postgresql;
  cargo-pgrx = cargo-pgrx_0_16_1;

  passthru.tests.extension = postgresqlTestExtension {
    inherit (finalAttrs) finalPackage;
    withPackages = [ "pgvector" ];
    sql = ''
      CREATE EXTENSION vectorscale CASCADE;
      CREATE TABLE document_embedding  (
          id BIGINT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
          embedding VECTOR(3)
      );

      INSERT INTO document_embedding (id, embedding) VALUES
      (10, '[1,2,4]'),
      (20, '[1,2,5]');

      CREATE INDEX document_embedding_idx ON document_embedding
      USING diskann (embedding vector_cosine_ops);
    '';
    asserts = [
      {
        query = "SELECT id FROM document_embedding WHERE embedding <-> '[1,2,3]' = 1";
        expected = "10";
        description = "Expected vector of row with ID=10 to have an euclidean distance from [1,2,3] of 1.";
      }
      {
        query = "SELECT id FROM document_embedding WHERE embedding <-> '[1,2,3]' = 2";
        expected = "20";
        description = "Expected vector of row with ID=20 to have an euclidean distance from [1,2,3] of 2.";
      }
    ];
  };

  meta = {
    # Upstream removed support for PostgreSQL 13 on 0.9.0: https://github.com/timescale/pgvectorscale/releases/tag/0.9.0
    broken = lib.versionOlder postgresql.version "14";
    homepage = "https://github.com/timescale/pgvectorscale";
    teams = [ lib.teams.flyingcircus ];
    description = "Complement to pgvector for high performance, cost efficient vector search on large workloads";
    license = lib.licenses.postgresql;
    platforms = postgresql.meta.platforms;
    changelog = "https://github.com/timescale/pgvectorscale/releases/tag/${finalAttrs.version}";
  };
})
